package _15_generics._15_3.coffee;

import net.mindview.util.Generator;

import java.util.Iterator;
import java.util.Random;

/**
 * 利用生成器生成对象的对象
 */
public class CoffeeGenerator implements Generator<Coffee>, Iterable<Coffee> {

    private Class[] types = {Latte.class,Mocha.class};

    private Random random = new Random(47);

    private int size = 0;

    public CoffeeGenerator(int size){
        this.size = size;
    }

    public CoffeeGenerator(){}

    @Override
    public Coffee next() {
        try {
            return (Coffee) types[random.nextInt(types.length)].newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Iterator<Coffee> iterator() {
        return new CoffeeIterator();
    }

    private class CoffeeIterator implements Iterator<Coffee>{

        private int count = size;

        @Override
        public boolean hasNext() {
            return count > 0;
        }

        @Override
        public Coffee next() {
            count--;
            return CoffeeGenerator.this.next();
        }
    }

    public static void main(String[] args) {
        CoffeeGenerator generator = new CoffeeGenerator();
        for (int i = 0; i< 5;i++){
            System.out.println(generator.next());
        }
        for (Coffee coffee : new CoffeeGenerator(5)){
            System.out.println(coffee);
        }
    }
}
